<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Order, Rebot as Rebots, Business, OrderGoods, BusinessArea, Goods, GoodsSpec, Region, Agent};
use think\Db;
use think\facade\Log;
use app\facade\Redis;

class Rebot extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Rebot')->setDescription('刷订单数据');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        (new Rebots())->where(['status' => 1])->chunk(1, function ($lists) {
            foreach ($lists as $list) {
                $result = json_decode($list['datas'], true);
                $time = explode(' ~ ', $result['fwtime']);
                if (empty($time[0]) || empty($time[1])) {
                    echo '时间范围出错';
                    continue;
                }
                $start = strtotime($time[0]);
                $end = strtotime($time[1]);
                //获取商家
                foreach ($result['business'] as $business) {
                    $created = date('Y-m-d', rand($start, $end)) . ' ' . gettime();
                    $fwtime = date('Y-m-d H', strtotime($created) + 3600) . ':00:00';
                    if ($fwtime > date('Y-m-d H:i:s')) {
                        echo '时间超过当前日期';
                        continue;
                    }
                    $rebot_total = 'rebot_total_id_' . $list['id'] . '_date_' . date('Y-m-d', strtotime($created));
                    $totalredis = Redis::get($rebot_total);
                    if (!$totalredis) {
                        Redis::setex($rebot_total, 30 * 86400, 0);
                        $totalredis = Redis::get($rebot_total);
                    }
                    if ($totalredis >= $result['allmoney']) {
                        echo '刷单累计金额超过限制';
                        continue;
                    }
                    //单个店铺刷单金额计算
                    $brebot_total = 'rebot_total_id_' . $list['id'] . '_date_' . date('Y-m-d', strtotime($created)) . '_' . $business;
                    $btotalredis = Redis::get($brebot_total);
                    if (!$btotalredis) {
                        Redis::setex($brebot_total, 30 * 86400, 0);
                        $btotalredis = Redis::get($btotalredis);
                    }
                    if ($btotalredis >= $result['money']) {
                        echo '刷单单店铺金额超过限制';
                        continue;
                    }
                    //获取商家服务区域
                    $area = (new BusinessArea())->where(['businessid' => $business, 'type' => [2, 3, 4]])->orderRaw('rand()')->find();
                    if (empty($area)) {
                        echo '商家无服务区域';
                        continue;
                    }
                    //获取商家项目
                    $goods = (new Goods())->orderRaw('rand()')->where(['businessid' => $business, 'type' => [1, 2, 3, 4], 'isSale' => 1, 'isdel' => 1])->find();
                    if (empty($goods)) {
                        echo '商家项目为空';
                        continue;
                    }
                    $spec = (new GoodsSpec())->orderRaw('rand()')->where(['goodid' => $goods['id'], 'isdel' => 1])->find();
                    if (empty($spec)) {
                        echo '商品规格为空';
                        continue;
                    }
                    $address['province'] = $area['province'];
                    $address['city'] = $area['city'];
                    $address['area'] = $area['area'];
                    $address['street'] = $area['street'];
                    $address['address'] = '';
                    $address['getaddress'] = '';
                    $address['lat'] = 0;
                    $address['lon'] = 0;
                    switch ($area['type']) {
                        case '2':
                            //随机获取区域
                            $city = (new Region())->where(['area_code' => $area['city'], 'level' => 2])->find();
                            $area = (new Region())->where(['parent_id' => $city['id'], 'level' => 3])->orderRaw('rand()')->find();
                            $street = (new Region())->where(['parent_id' => $area['id'], 'level' => 4])->orderRaw('rand()')->find();
                            $address['area'] = $area['area_code'];
                            $address['street'] = $street['id'];
                            break;
                        case '3':
                            $area = (new Region())->where(['area_code' => $area['area'], 'level' => 3])->find();
                            $street = (new Region())->where(['parent_id' => $area['id'], 'level' => 4])->orderRaw('rand()')->find();
                            $address['street'] = $street['id'];
                            break;
                        case '4':
                            break;
                        default:
                            echo '超出范围，无法服务';
                            continue;
                    }
                    $spec['number'] = $goods['starbuy'] ?? 1;
                    if ($spec['price'] * $spec['number'] < 50) {
                        $spec['number'] = $spec['number'] * 2;
                    }
                    $result['user'] = array_values($result['user']);
                    $namekey = rand(0, count($result['user']));
                    if ($namekey > 0) {
                        $namekey = $namekey - 1;
                    }
                    $mobilekey = rand(0, count($result['user']));
                    if ($mobilekey > 0) {
                        $mobilekey = $mobilekey - 1;
                    }
                    $addresskey = rand(0, count($result['user']));
                    if ($addresskey > 0) {
                        $addresskey = $addresskey - 1;
                    }
                    $address['name'] = $result['user'][$namekey]['name'];
                    $address['mobile'] = $result['user'][$mobilekey]['mobile'];
                    $address['address'] = $result['user'][$addresskey]['address'];
                    //订单
                    $order = [
                        'type' => $goods['type'],
                        'user_id' => rand(74, 1074),
                        'ordersn' => reordersn(new Order()),
                        'businessid' => $business,
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'street' => $address['street'],
                        'getaddress' => $address['getaddress'],
                        'address' => $address['address'],
                        'lat' => $address['lat'],
                        'lon' => $address['lon'],
                        'total' => 0,
                        'coupon' => 0,
                        'times' => $fwtime ?? '',
                        'remark' => '',
                        'coupontotal' => 0,
                        'zhekoutotal' => 0,
                        'othertotal' => 0,
                        'total' => 0,
                        'ptotal' => 0,
                        'putstatus' => 2,
                        'created' => $created,
                        'paytimes' => $created,
                        'fwtimes' => date('Y-m-d H:i:s', strtotime($created) + rand(60, 600)),
                        'puttime' => date('Y-m-d H:i:s', strtotime($created) + rand(300, 600)),
                        'finishtimes' => date('Y-m-d H:i:s', strtotime($created) + rand(3000, 3600)),
                        'caceltimes' => date('Y-m-d H:i:s', strtotime($created) + rand(3000, 3600)),
                        'issystem' => 2
                    ];
                    $order['ptotal'] += $spec['price'] * $spec['number'];
                    $order['total'] = $order['ptotal'];
                    if ($order['total'] == 0) {
                        $order['status'] = 2;
                    }
                    $status = [3, 4, 5];
                    $statuskey = rand(0, count($status));
                    if ($statuskey > 0) {
                        $statuskey = $statuskey - 1;
                    }
                    $order['status'] = $status[$statuskey];
                    $ordergoods = [
                        'ordersn' => $order['ordersn'],
                        'businessid' => $goods['businessid'],
                        'classid' => $goods['classid'],
                        'sonsid' => $goods['sonsid'],
                        'goodsid' => $goods['id'],
                        'goodspecid' => $spec['id'],
                        'title' => $goods['title'],
                        'images' => $goods['images'],
                        'name' => $spec['name'],
                        'number' =>  $spec['number'],
                        'unmit' => $spec['unmit'],
                        'price' =>   $spec['price'],
                        'total' => floor($spec['number'] * $spec['price'] * 100) / 100,
                        'created' => $created,
                    ];
                    Db::startTrans();
                    try {
                        (new Order())->allowfield(true)->save($order);
                        (new OrderGoods())->allowfield(true)->save($ordergoods);
                        Redis::setex($rebot_total, 5 * 86400,  $totalredis + $order['total']);
                        Redis::setex($brebot_total, 5 * 86400, $btotalredis + $order['total']);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        echo $e->getMessage();
                        continue;
                    }
                    echo '插入成功';
                }
            }
        });
    }
}